package com.example.kuaizu.utils;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import kuaizu.common.constp.KuaiZuConst;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

//文件相关操作
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class FileUtils {
    private static final Logger log = LoggerFactory.getLogger(FileUtils.class);
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    @Value("${dromara.x-file-storage.aliyun-oss[0].access-key}")
    private  String accessKeyId;
    @Value("${dromara.x-file-storage.aliyun-oss[0].secret-key}")
    private  String accessKeySecret;
    @Value("${dromara.x-file-storage.aliyun-oss[0].bucket-name}")
    // 填写Bucket名称，例如examplebucket。
    private  String bucketName;
    @Value("${dromara.x-file-storage.aliyun-oss[0].base-path}")
    private String path;
    @Value("${alioss.zd-endpoint}")
    String endpoint;

    /**
     * 删除文件  填写文件完整路径。文件完整路径中不能包含Bucket名称。
     */
    public  String deleteFile(String url) {
        url = path+url;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            log.info("删除的路径:{}",url);
            ossClient.deleteObject(bucketName, url);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return "删除成功";
    }

    /**
     * 获取指定目录下的文件列表
     *
     * @param url 名称
     * @return
     */
    public List<String> listAllFileNames(String url) {
        List<String> fileNames = new ArrayList<>();
        try {
            ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
            listObjectsRequest.setPrefix(url);
            // 列举文件 指定目录下的文件
            ObjectListing objectListing = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret).listObjects(listObjectsRequest);
            for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                fileNames.add(objectSummary.getKey());
            }
        } catch (Exception e) {
            log.error("获取文件列表失败", e);
            throw new RuntimeException("获取文件列表失败", e);
        }
        return fileNames;
    }


    /**
     * 删除文件  填写文件完整路径。文件完整路径中不能包含Bucket名称。
     */
    public String deleteFile(String url, String bucketName) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            log.info("删除的路径:{}", url);
            ossClient.deleteObject(this.bucketName, url);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return "删除成功";
    }

    /**
     * 图片上穿
     *
     * @param url 名称
     * @return
     */
    public String updateFile(MultipartFile file) {
        String fileName = KuaiZuConst.KUAIZU_IMG_URL + file.getOriginalFilename(); // 注意应该是 getOriginalFilename() 而不是 getName()
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, file.getInputStream());
            ossClient.putObject(putObjectRequest);
            return endpoint + "/" + bucketName + "/" + fileName;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (Exception e) {
            System.out.println("Caught an Exception, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return "上传失败";
    }

}



